/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jwu2.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import jwu2.log.Logger;
import lombok.Cleanup;

/**
 *
 * @author Rolf
 */
public class Config {
    private static Config singleton;
    
    private static final String filename = "JWU2Config.dat";
    private Map<String, String> values;
    
    
    
    private Config() {
        loadConfig();
    }

    public static Config singleton() {
        if( singleton == null ) {
            singleton = new Config();
        }
        
        return singleton;
    }
    
    public void setValue(String key, String value) {
        values.put(key, value);
        
        saveConfig();
    }
    
    public String getValue(String key) {
        return values.get(key);
    }

    public long getLastIndexServerUpdate() {
        return parseLong(getValue("lastIndexServerUpdate"));
    }
    
    public void setLastIndexServerUpdate(long timestamp) {
        setValue("lastIndexServerUpdate", ""+timestamp);
    }

    public void setDeleteBeforeUpdate(boolean b) {
        setValue("deletebeforeupdate", ""+b);
    }
    
    public boolean shouldDeleteBeforeUpdate() {
        return parseBoolean(getValue("deletebeforeupdate"));
    }
    
    private void loadDefaults() {
        setValue("lastIndexServerUpdate", ""+0);
    }

    private boolean parseBoolean(String value) {
        try {
            return Boolean.parseBoolean(value);
        }
        catch(Exception e) {
            Logger.logln("Error converting string to boolean: "+e);
        }
        
        return false;
    }
    
    private long parseLong(String value) {
        try {
            return Long.parseLong(value);
        }
        catch(Exception e) {
            Logger.logln("Error converting string to long: "+e);
        }
        
        return Long.MIN_VALUE;
    }
    
    private synchronized void saveConfig() {
        try {
            @Cleanup ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
            
            out.writeObject(values);
            out.flush();
        }
        catch(Exception e) {
            Logger.logln("Error saving JWU2Config: "+e);
        }
    }

    private synchronized void loadConfig() {
        try {
            @Cleanup ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
            
            values = (HashMap<String, String>) in.readObject();
        }
        catch(Exception e) {
            Logger.logln("Error loading JWU2Config: "+e);

            values = new HashMap<String, String>();
            loadDefaults();
        }
    }
}
